/*
 * @Description: 验证码按钮
 * @Author: iamsmiling
 * @Date: 2021-06-13 15:29:37
 * @LastEditTime: 2021-06-15 08:41:29
 */

import 'dart:async';

import 'package:flutter/material.dart';

WidgetBuilder _defaultTextBuilder = (BuildContext context) {
  return Container(
    constraints: BoxConstraints(minWidth: 100),
    padding: EdgeInsets.symmetric(vertical: 15, horizontal: 20),
    decoration: BoxDecoration(
        gradient:
            LinearGradient(colors: [Color(0xff1bbd8d), Color(0xff14ca94)])),
    child: Text(
      "获取验证码",
      style: TextStyle(
          fontSize: 13, color: Colors.white, fontWeight: FontWeight.w400),
    ),
  );
};

Widget Function(BuildContext, int) _defaultCountBuilder =
    (BuildContext context, int i) {
  return Container(
    constraints: BoxConstraints(minWidth: 100),
    padding: EdgeInsets.symmetric(vertical: 15, horizontal: 20),
    decoration: BoxDecoration(
        gradient:
            LinearGradient(colors: [Color(0xff1bbd8d), Color(0xff14ca94)])),
    child: Text(
      "$i后重新发送",
      style: TextStyle(
          fontSize: 13, color: Colors.white, fontWeight: FontWeight.w400),
    ),
  );
};

class CaptchaButton extends StatefulWidget {
  final WidgetBuilder? textBuilder;
  final Widget Function(BuildContext, int)? countBuilder;

  final Function()? onPressed;
  CaptchaButton({Key? key, this.textBuilder, this.countBuilder, this.onPressed})
      : super(key: key);

  @override
  _CaptchaButtonState createState() => _CaptchaButtonState();
}

class _CaptchaButtonState extends State<CaptchaButton> {
  int _initialCount = 60;
  int _maxCount = 60;

  late StreamController<int> _streamController;

  late Timer _timer;

  @override
  void initState() {
    _streamController = StreamController<int>();
    super.initState();
  }

  void _onPressed() {
    if (widget.onPressed != null) {
      widget.onPressed!();
    }
    print("我被电击了");
    _countDown();
  }

  void _countDown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_maxCount <= 0) {
        timer.cancel();
        _maxCount = _initialCount;
      } else {
        _maxCount--;
      }

      _streamController.add(_maxCount);
    });
  }

  @override
  void dispose() {
    _streamController.close();
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
        initialData: _initialCount,
        stream: _streamController.stream,
        builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
          bool enabled = snapshot.data == _initialCount;
          return GestureDetector(
            onTap: enabled ? _onPressed : () {},
            child: enabled
                ? Builder(builder: widget.textBuilder ?? _defaultTextBuilder)
                : Builder(builder: (BuildContext context) {
                    return widget.countBuilder == null
                        ? _defaultCountBuilder(
                            context, snapshot.data ?? _initialCount)
                        : widget.countBuilder!(
                            context, snapshot.data ?? _initialCount);
                  }),
          );
        });
  }
}
